package com.leecode.xiehf.page_02;

import com.leecode.Printer;

/**
 * 给定一个二维网格和一个单词，找出该单词是否存在于网格中。
 * <p>
 * 单词必须按照字母顺序，通过相邻的单元格内的字母构成，其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/word-search
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Solution_0079 extends Printer {

    public static void main(String[] args) {
        Solution_0079 solution = new Solution_0079();
        boolean s = solution.exist(new char[][]
                        {
                                {'A', 'B', 'C', 'E'},
                                {'S', 'F', 'C', 'S'},
                                {'A', 'D', 'E', 'E'}
//                                {'a', 'b'}, {'c', 'd'}
                        }
                , "SEE");
        System.out.println(s);
    }

    public boolean exist(char[][] board, String word) {
        if (board.length == 0 || word.length() == 0) {
            return false;
        }
        int height = board.length;
        int width = board[0].length;
        boolean[][] dp = new boolean[height][width];
        int[][] direct = new int[][]
                {
                        {1, 0}, // right
                        {0, 1}, // down
                        {-1, 0}, // left
                        {0, -1} // up
                };
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (board[i][j] == word.charAt(0)) {
                    dp[i][j] = true;
                    if (dfs(i, j, 1, word, direct, board, dp)) {
                        return true;
                    } else {
                        dp[i][j] = false;
                    }
                }
            }
        }
        return false;
    }

    private boolean dfs(int i, int j, int idx, String word, int[][] direct, char[][] board, boolean[][] dp) {
        if (idx == word.length()) {
            return true;
        }
        for (int[] d : direct) {
            int newX = i + d[0];
            int newY = j + d[1];
            if (!valid(newX, newY, board.length, board[0].length)) {
                continue;
            }
            if (dp[newX][newY]) {
                continue;
            }
            if (board[newX][newY] != word.charAt(idx)) {
                continue;
            }
            dp[newX][newY] = true;
            if (dfs(newX, newY, idx + 1, word, direct, board, dp)) {
                return true;
            } else {
                dp[newX][newY] = false;
            }
        }
        return false;
    }

    private boolean valid(int x, int y, int height, int width) {
        return x >= 0 && x < height && y >= 0 && y < width;
    }
}
